package com.hillfly.mybatis.shard;

import com.hillfly.mybatis.shard.strategy.Strategy;
import com.hillfly.mybatis.shard.strategy.impl.DoNotStrategy;

public class ShardHelper {
    private static final ThreadLocal<ShardParams> LOCAL_SHARD_PARAMS = new ThreadLocal<ShardParams>();

    /**
     * 设置 ShardParams 参数
     *
     * @param shardParams
     */
    protected static void setLocalShardParams(ShardParams shardParams) {
        LOCAL_SHARD_PARAMS.set(shardParams);
    }

    /**
     * 获取 ShardParams 参数
     *
     * @return
     */
    public static ShardParams getLocalShardParams() {
        return LOCAL_SHARD_PARAMS.get();
    }

    /**
     * 移除本地变量
     */
    public static void clearShardParams() {
        LOCAL_SHARD_PARAMS.remove();
    }

    public static boolean isShardParamsEmpty() {
        return getLocalShardParams() == null;
    }

    public static void startShard(Strategy strategy) {
        ShardParams shardParams = (new ShardParams()).setStrategy(strategy).setExcludes(null).setIncludes(null);
        setLocalShardParams(shardParams);
    }

    public static void startShard(Strategy strategy, String[] excludes, String[] includes) {
        ShardParams shardParams = new ShardParams().setStrategy(strategy).setExcludes(excludes).setIncludes(includes);
        setLocalShardParams(shardParams);
    }

    public static void stopShard() {
        ShardParams shardParams = (new ShardParams()).setStrategy(new DoNotStrategy()).setExcludes(null).setIncludes(null);
        setLocalShardParams(shardParams);
    }
}
